package voja.android.mysql;

import voja.android.mysql.R;

import voja.android.mysql.Prefs;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    
	View.OnClickListener onPrefs = new OnClickListener() {
		public void onClick(View v) {
			Intent settingsActivity = new Intent(getBaseContext(), Prefs.class);
			startActivity(settingsActivity);
		}
	};
	View.OnClickListener onSubmit = new OnClickListener() {
		public void onClick(View v) {
			TextView tSql = (TextView)findViewById(R.id.txtQuery);
			String sql = tSql.getText().toString();
			
			TextView to = (TextView)findViewById(R.id.output);
			try{
				to.setText(Mysql.select(sql));
			}catch(Exception e) {
				to.setText(e.toString());
			}
		}
	};
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        findViewById(R.id.btnPrefs).setOnClickListener(onPrefs);
        findViewById(R.id.btnSubmit).setOnClickListener(onSubmit);
        
        loadDBCredentials();
    }
    
    private Boolean loadDBCredentials() {
    	Boolean retval = false;
    	SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    	String host = prefs.getString("cHost", "localhost");
		String port = prefs.getString("cPort", "3306");
		String db = prefs.getString("cDatabase", "test");
		String user = prefs.getString("cUsername", "root");
		String pass = prefs.getString("cPassword", "");
		try {
			Mysql.updateConnection(host, port, db, user, pass);
		}catch(Exception e) {
			Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG);
		}
    	return retval;
    }
    
    public void onDestroy() {
    	try {
    		Mysql.close();
    	}catch(Exception e) {
    		Log.e("mysql", e.toString());
    	}
    }
}